<template>
  <div class="field-array-demo">
    <h2>FieldArray 完整功能演示</h2>

    <Form :initial-values="initialValues" @submit="onSubmit">
      <Field name="name">
        <template #default="data">
          <input v-model="data.field.value" />
        </template>
      </Field>
      <FieldArray
        v-slot="{
          fields,
          push,
          remove,
          prepend,
          insert,
          swap,
          move,
          update,
          replace,
        }"
        name="links"
      >
        <!-- 数组操作按钮 -->
        <div class="array-controls">
          <ElButton
            type="primary"
            @click="push({ id: Date.now(), name: '', url: '' })"
          >
            添加到最后
          </ElButton>
          <ElButton
            type="success"
            @click="prepend({ id: Date.now(), name: '', url: '' })"
          >
            添加到开头
          </ElButton>
          <ElButton
            type="warning"
            @click="insert(1, { id: Date.now(), name: '', url: '' })"
          >
            插入到第2位
          </ElButton>
          <ElButton
            type="info"
            @click="
              replace([{ id: 1, name: '重置', url: 'https://example.com' }])
            "
          >
            重置数组
          </ElButton>
        </div>

        <!-- 数组项列表 -->
        <div class="array-items">
          <div
            v-for="(field, idx) in fields"
            :key="field.key"
            class="array-item"
          >
            <div class="item-header">
              <span class="item-index">第 {{ idx + 1 }} 项</span>
              <span class="item-info">
                Key: {{ field.key }} | 第一个: {{ field.isFirst }} | 最后一个:
                {{ field.isLast }}
              </span>
            </div>

            <div class="item-fields">
              <div class="field-group">
                <label>ID:</label>
                <Field
                  :name="`links[${idx}].id`"
                  :validate-on-blur="false"
                  :validate-on-input="true"
                  type="number"
                >
                  <template #default="data">
                    <input v-model="data.field.value" />
                  </template>
                </Field>
              </div>

              <div class="field-group">
                <label>*名称:</label>
                <Field
                  :name="`links[${idx}].name`"
                  :rules="nameRules"
                  :validate-on-blur="false"
                  :validate-on-input="true"
                  placeholder="请输入名称"
                  type="text"
                />
                <ErrorMessage
                  :name="`links[${idx}].name`"
                  as="p"
                  class="animate__animated animate__bounce mt-1 text-sm text-red-500"
                />
              </div>

              <div class="field-group">
                <label>URL:</label>
                <Field
                  :name="`links[${idx}].url`"
                  placeholder="请输入URL"
                  type="url"
                />
              </div>
            </div>

            <!-- 项目操作按钮 -->
            <div class="item-controls">
              <ElButton size="small" type="danger" @click="remove(idx)">
                删除
              </ElButton>
              <ElButton
                size="small"
                type="warning"
                @click="
                  update(idx, {
                    id: '6666666666',
                    name: '已更新',
                    url: field.value.url,
                  })
                "
              >
                更新
              </ElButton>
              <ElButton
                v-if="idx > 0"
                size="small"
                type="info"
                @click="move(idx, idx - 1)"
              >
                上移
              </ElButton>
              <ElButton
                v-if="idx < fields.length - 1"
                size="small"
                type="info"
                @click="move(idx, idx + 1)"
              >
                下移
              </ElButton>
              <ElButton
                v-if="idx > 0"
                size="small"
                type="success"
                @click="swap(idx, idx - 1)"
              >
                与上一个交换
              </ElButton>
            </div>
          </div>
        </div>

        <!-- 数组信息显示 -->
        <div class="array-info">
          <p>数组长度: {{ fields.length }}</p>
          <p>
            数组内容:
            {{
              JSON.stringify(
                fields.map((f) => f.value),
                null,
                2,
              )
            }}
          </p>
        </div>
      </FieldArray>

      <!-- 提交按钮 -->
      <div class="submit-section">
        <ElButton native-type="submit" size="large" type="primary">
          提交表单
        </ElButton>
      </div>
    </Form>
  </div>
</template>

<script setup lang="ts">
import { toTypedSchema } from '@vee-validate/zod';
import { ElButton, ElMessage } from 'element-plus';
import { ErrorMessage, Field, FieldArray, Form } from 'vee-validate';
import z from 'zod';

import 'animate.css';
// 初始值设置
const initialValues = {
  name: '123',
  links: [
    { id: 1, name: 'GitHub', url: 'https://github.com/logaretm' },
    { id: 2, name: 'Vue', url: 'https://vuejs.org' },
    { id: 3, name: 'VeeValidate', url: 'https://vee-validate.logaretm.com' },
  ],
};

const nameRules = toTypedSchema(
  z
    .string({
      message: '姓名至少需要2个字符',
    })
    .min(2, { message: '姓名至少需要2个字符' }),
);

const onSubmit = (_values: any, { resetForm }: any) => {
  // 表单验证通过后的处理逻辑
  ElMessage.success(`提交成功 ${JSON.stringify(_values)}`);
  // 方法1: 使用 FormActions 对象重置表单（推荐）
  resetForm();
};
</script>

<style scoped>
/* 响应式设计 */
@media (max-width: 768px) {
  .item-fields {
    grid-template-columns: 1fr;
  }

  .array-controls {
    flex-direction: column;
  }

  .item-controls {
    justify-content: center;
  }
}

.field-array-demo {
  max-width: 800px;
  padding: 20px;
  margin: 0 auto;
}

.array-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.array-items {
  margin-bottom: 20px;
}

.array-item {
  padding: 15px;
  margin-bottom: 15px;
  background: #fafafa;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
}

.item-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 10px;
  margin-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.item-index {
  font-weight: bold;
  color: #409eff;
}

.item-info {
  font-size: 12px;
  color: #666;
}

.item-fields {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 15px;
  margin-bottom: 15px;
}

.field-group {
  display: flex;
  flex-direction: column;
}

.field-group label {
  margin-bottom: 5px;
  font-size: 12px;
  color: #666;
}

.item-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.array-info {
  padding: 15px;
  margin-bottom: 20px;
  background: #f0f0f0;
  border-radius: 8px;
}

.array-info p {
  margin: 5px 0;
  font-family: monospace;
  font-size: 12px;
}

.submit-section {
  padding-top: 20px;
  text-align: center;
  border-top: 1px solid #e0e0e0;
}
</style>
